﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.Shell.Interop;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio.TextTemplating.VSHost;
using System.IO;
using System.Diagnostics;
using System.Reflection;

namespace Liekhus.Xaf.BusinessObjectDesigner
{
    [Guid("486FD8D5-6217-4e43-8EEA-46F05A2883C3")]
    [ProvideCodeGenerator(typeof(XAFBODCustomTool), "Patrick Liekhus XAF/DSL Code Generator", "Custom tool that generates files based on the DevExpress XAF concepts using a DSL Model", true)]
    public class XAFBODCustomTool : TemplatedCodeGenerator
    {
        protected override byte[] GenerateCode(string inputFileName, string inputFileContent)
        {
            const string ModelFileNameMarker = "%MODELFILENAME%";
            const string ResourceName = @"Liekhus.Xaf.BusinessObjectDesigner.CustomCode.CustomCodeTemplate.tt";

            // Load the text template from the embedded resource
            string templateCode = null;
            using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(ResourceName))
            {
                Debug.Assert(stream != null, "Error - could not find the resource");
                StreamReader reader = new StreamReader(stream);
                templateCode = reader.ReadToEnd();
                reader.Close();
            }

            Debug.Assert(templateCode.Contains(ModelFileNameMarker),
                "Error - the template code does not contain the expected model file name marker");


            // Substitute the real model file name into the template code
            templateCode = templateCode.Replace(ModelFileNameMarker, inputFileName);

            // Delegate the rest of the work to the base class.
            // This will run the T4 transformation and return the
            // result.
            return base.GenerateCode(inputFileName, templateCode);
        }
    }
}
